package com.atguigu.tingshu.account.api;

import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.login.GuiguLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountLockVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "用户账户管理")
@RestController
@RequestMapping("api/account/userAccount")
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserAccountApiController {

	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private RechargeInfoService rechargeInfoService;
//	/api/account/userAccount/findUserRechargePage/1/10
	@GetMapping("findUserRechargePage/{pageNum}/{pageSize}")
	@Operation(summary = "查询充值记录")
	@GuiguLogin
	public Result findUserRechargePage(@PathVariable("pageNum")Long pageNum,
									   @PathVariable("pageSize")Long pageSize){

		Page<RechargeInfo> page = rechargeInfoService.page(new Page<>(pageNum, pageSize),
				Wrappers.lambdaQuery(RechargeInfo.class)
						.eq(RechargeInfo::getUserId, AuthContextHolder.getUserId())
						.orderByDesc(RechargeInfo::getCreateTime));

		List<UserAccountDetail> details = page.getRecords().stream().map(rechargeInfo -> {
			UserAccountDetail detail = new UserAccountDetail();
			detail.setUserId(AuthContextHolder.getUserId());
			detail.setTitle("充值");
			detail.setOrderNo(rechargeInfo.getOrderNo());
			detail.setAmount(rechargeInfo.getRechargeAmount());
			detail.setTradeType(SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT);

			return detail;
		}).collect(Collectors.toList());

		Page<UserAccountDetail> detailsPage = new Page<>(pageNum,pageSize);
		detailsPage.setTotal(page.getTotal());
		detailsPage.setPages(page.getPages());
		detailsPage.setRecords(details);

		return Result.ok(detailsPage);
	}


	//GetMapping: 传对象，以请求参数拼接的形式传参  url?id=xx&name=xx
	@Operation(summary = "内部接口：校验并扣除账户余额、保存账户交易流水")
	@GuiguLogin
	@PostMapping("checkAndDeduction")
	public Result<Boolean> checkAndDeduction(@RequestBody AccountLockVo accountLockVo){
		boolean flag = userAccountService.checkAndDeduction(accountLockVo);
		return Result.ok(flag);
	}
	///api/account/userAccount/getAvailableAmount
	@Operation(summary = "查询用户账户余额")
	@GuiguLogin
	@GetMapping("getAvailableAmount")
	public Result getAvailableAmount(){
		/*
		@Schema(description = "账户总金额")
		@TableField("total_amount")
		private BigDecimal totalAmount;
				- 账户充值和收入的总金额： totalAmount= 锁定金额+可用金额
				-
		@Schema(description = "锁定金额")
		@TableField("lock_amount")
		private BigDecimal lockAmount;
				- 用户购买产品但是还未支付 等待用户确认支付
		@Schema(description = "可用金额")
		@TableField("available_amount")
		private BigDecimal availableAmount;
				- 账户可用的金额： totalAmount - lockAmount
		@Schema(description = "总收入")
		@TableField("total_income_amount")
		private BigDecimal totalIncomeAmount;

		@Schema(description = "总支出")
		@TableField("total_pay_amount")
		private BigDecimal totalPayAmount;
		 */
		UserAccount userAccount = userAccountService.getOne(Wrappers
				.lambdaQuery(UserAccount.class)
				.eq(UserAccount::getUserId, AuthContextHolder.getUserId())
				.select(UserAccount::getAvailableAmount));
		if(userAccount==null){
			throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
		}
		return Result.ok(userAccount.getAvailableAmount());
	}

	@PostMapping("saveAccount/{userId}")
	public Result saveAccount(@PathVariable Long userId){
		this.userAccountService.saveAccount(userId);
		return Result.ok();
	}
}

